import cv2
import pyautogui
from ultralytics import YOLO
import time
import sys
import os
import subprocess
from moveFb模块 import movefb
import win32gui
import 检测框模块
from find_class_module import find_class_and_perform_action
from yolo2.find_and_perform_action_module import find_and_perform_action
from yolo2.yolo找图模块 import click_target_image
from yolo2.循环找图模块 import run_action_condition_found, run_action_condition_not_found


if os.name == 'nt':
    import ctypes
    kernel32 = ctypes.windll.kernel32
    kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
GREEN = '\033[92m'
# 定义重置颜色的 ANSI 转义序列
RESET = '\033[0m'


def draw_detection_boxes(screenshot, results):
    for result in results:
        boxes = result.boxes.cpu().numpy()
        for box in boxes:
            class_id = int(box.cls[0])
            x1, y1, x2, y2 = box.xyxy[0].astype(int)
            center_x = int((x1 + x2) / 2)
            center_y = int((y1 + y2) / 2)

            # 在图像上绘制检测框
            cv2.rectangle(screenshot, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(screenshot, f"Class {class_id}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    return screenshot


def main():
    if hasattr(检测框模块, 'MODULE_LOADED') and 检测框模块.MODULE_LOADED:
        print("检测框模块已正确加载")
    else:
        print("检测框模块加载失败")

    # 禁用 pyautogui 的安全保护机制
    pyautogui.FAILSAFE = False

    # 加载 YOLOv8n 模型并指定使用GPU .to('cuda')
    model = YOLO(r"H:\yol\yolo\v11\runs\detect\train41\weights\best.pt")

    hwnd = 检测框模块.find_window()
    if hwnd is None:
        print("未找到标题中包含'梦幻西游'的窗口")
    else:
        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        window_width = right - left
        window_height = bottom - top

        print("主程序启动，正在检查77")
        # 封装的检查和执行动作逻辑，没找到则
        def action_a():
            pyautogui.hotkey('alt', 'e')
        find_class_and_perform_action(hwnd, model, 18, action_a)
        print("先加血")
        movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=93, offset_x=-10,
               offset_y=-10, 置信度=0.3, click_type='right')
        print("加好血了，点击合成旗")

        def action_a():
            print("右键点击合成旗")
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=18, offset_x=-10,
                   offset_y=-10, 置信度=0.3, click_type='right')
            print("右键点击成功")
        find_class_and_perform_action(hwnd, model, 19, action_a)
        pyautogui.hotkey('alt', 'e')

        def action_a():
            print("点击帮派传送点")
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=19, offset_x=-10, offset_y=-10,
                   置信度=0.3, click_type='left')
            print(f"{GREEN}没点到，继续点{RESET}")
        find_class_and_perform_action(hwnd, model, 9, action_a)

        print(f"{GREEN}点击成功，来到帮派主管这里了{RESET}")
        # 鼠标向左移动20个像素，点击一次
        pyautogui.hotkey('f9')
        print("屏蔽路人")
        pyautogui.moveRel(-15, -85)
        pyautogui.click()

        # 封装的检查和执行动作逻辑，没找到则
        def action_a():
            pyautogui.hotkey('F9')
            print(f"{GREEN}点击帮派主管{RESET}")
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=9, offset_x=-10,
                   offset_y=-10, 置信度=0.3, click_type='left', success_image=9, 如果不成功循环执行的次数=1)
            pyautogui.click()
            # 检查类别 148 和类别 5 是否出现
            screenshot = 检测框模块.get_window_screenshot(hwnd)
            results = model(screenshot)
            class_ids = [int(box.cls[0]) for result in results for box in result.boxes.cpu().numpy()]
            if 148 not in class_ids and 5 in class_ids:
                # 点一下类别 5 关掉界面
                for result in results:
                    boxes = result.boxes.cpu().numpy()
                    for box in boxes:
                        class_id = int(box.cls[0])
                        if class_id == 5:
                            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=5, offset_x=-10,
                                   offset_y=-10, 置信度=0.3, click_type='left')
                            break
                # 重启这个任务
                action_a()

            print(f"{GREEN}没点到，继续点{RESET}")
        find_class_and_perform_action(hwnd, model, 148, action_a)
        print(f"{GREEN}点击帮派主管成功{RESET}")

        def action_a():
            print("点击选项一")
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=148, offset_x=-10,
                   offset_y=-10, 置信度=0.3, click_type='left', success_image=9, 如果不成功循环执行的次数=1)
            pyautogui.click()
            pyautogui.click()
        find_class_and_perform_action(hwnd, model, 14, action_a)

        pyautogui.click()
        # 封装的检查和执行动作逻辑，没找到则
        def action_a():
            pyautogui.moveRel(50, 35)
            pyautogui.hotkey('F5')

            pyautogui.click()
            time.sleep(0.1)
        find_class_and_perform_action(hwnd, model, 13, action_a)

        # 封装的检查和执行动作逻辑，没找到则
        def action_a():
            print(f"{GREEN}点击厢房门口{RESET}")
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=13, offset_x=-60,
                   offset_y=-50, 置信度=0.3, click_type='left')
            print(f"{GREEN}点中了，继续点直到进入厢房{RESET}")
        find_class_and_perform_action(hwnd, model, 10, action_a)

        def action_a():  # 点玄武堂总管接任务
            print(f"{GREEN}点总管{RESET}")
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=10, offset_x=-10,
                   offset_y=-30, 置信度=0.3, click_type='left')
            pyautogui.click()

        find_class_and_perform_action(hwnd, model, 148, action_a)
        print(f"{GREEN}点选项一接任务{RESET}")
        movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=148, offset_x=-10,
               offset_y=-10, 置信度=0.3, click_type='left')

        # 保存游戏窗口截图
        screenshot = 检测框模块.get_window_screenshot(hwnd)
        save_dir = r"h:\yol\ultralytics\datasets\mycp\images"
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        save_path = os.path.join(save_dir, f"screenshot_{int(time.time())}.png")
        cv2.imwrite(save_path, screenshot)
        print(f"游戏窗口截图已保存到 {save_path}")

        def action_a():
            print("没香了，吃香。")
            pyautogui.hotkey('alt', 'e')
            movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=81, offset_x=0, offset_y=0,
                   置信度=0.3, click_type='right')
        find_class_and_perform_action(hwnd, model, 43, action_a)

    print(f"{GREEN}主程序所有任务完成{RESET}")
    import 分地图2
    分地图2.main()
    print(f"{GREEN}尝试启动分地图2{RESET}")
    sys.exit()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()
